<?php

declare (strict_types = 1);

namespace app\admin\model\admin;

use app\common\model\admin\Api as ApiModel;
use app\admin\model\admin\MenuApi as MenuApiModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 后台用户权限模型
 * Class Api
 */
class Api extends ApiModel
{
    /**
     * 获取权限列表
     * @param array $param
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getList(array $param = []): array
    {
        $all = static::getAll($param);
        return $this->getTreeData($all);
    }
    /**
     * 新增记录
     * @param array $data
     * @return bool|false
     */
    public function add(array $data): bool
    {
        $data['create_time'] = time();
        $data['update_time'] = time();
        return $this->allowField(['name', 'pid', 'url', 'sort','create_time','update_time'])->save($data);
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function edit(array $data): bool
    {
        // 判断上级角色是否为当前子级
        if ($data['pid'] > 0) {
            // 获取所有上级id集
            $parentIds = $this->getTopApiIds($data['pid']);
            if (in_array($this['api_id'], $parentIds)) {
                $this->error = '上级权限不允许设置为当前子权限';
                return false;
            }
        }
        $data['update_time'] = time();
        return $this->allowField(['name', 'pid', 'url', 'sort','update_time'])->save($data);
    }

    /**
     * 删除权限
     * @return bool
     */
    public function remove(): bool
    {
        // 判断是否存在下级权限
        $pid = self::detail(['pid' => $this['api_id']]);
        if ($pid) {
            $this->error = '当前权限下存在子API：'.$pid['name'].'，请先删除';
            return false;
        }
        // 判断是否被分配
        $MenuApi = MenuApiModel::detail(['api_id' => $this['api_id']]);
        if ($MenuApi) {
            $this->error = '当前AP已被分配给菜单ID：'.$MenuApi['menu_id'].'，请先取消分配';
            return false;
        }
        return $this->delete();
    }

    /**
     * 获取所有上级id集
     * @param int $apiId
     * @param null $all
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function getTopApiIds(int $apiId, $all = null): array
    {
        static $ids = [];
        is_null($all) && $all = $this->getAll();
        foreach ($all as $item) {
            if ($item['api_id'] == $apiId && $item['pid'] > 0) {
                $ids[] = $item['pid'];
                $this->getTopApiIds($item['pid'], $all);
            }
        }
        return $ids;
    }

    /**
     * 获取树状列表
     * @param array $list
     * @param int $parentId
     * @return array
     */
    private function getTreeData(array &$list, int $parentId = 0): array
    {
        $data = [];
        foreach ($list as $key => $item) {
            if ($item['pid'] == $parentId) {
                $children = $this->getTreeData($list, (int)$item['api_id']);
                !empty($children) && $item['children'] = $children;
                $data[] = $item;
                unset($list[$key]);
            }
        }
        return $data;
    }

    /**
     * 获取权限列表 jstree格式
     * @param int|null $role_id 当前角色id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getJsTree(int $role_id = null): string
    {
        $apiIds = is_null($role_id) ?[]:$role_id;
        $jsTree = [];
        foreach ($this->getAll() as $item) {
            $jsTree[] = [
                'id' => $item['api_id'],
                'parent' => $item['pid'] > 0 ? $item['pid'] : '#',
                'text' => $item['name'],
                'state' => [
                    'selected' => (in_array($item['api_id'], $apiIds) && !$this->hasChildren($item['api_id']))
                ]
            ];
        }
        return jsonEncode($jsTree);
    }

    /**
     * 是否存在子集
     * @param $api_id
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function hasChildren($api_id): bool
    {
        foreach (self::getAll() as $item) {
            if ($item['pid'] == $api_id)
                return true;
        }
        return false;
    }

}